package com.teradata.feedProc;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import com.teradata.feedProc.beans.FeedInfo;

/**
 * Utility class for performing file specific operations.
 */
public class FileUtils {

	/**
	 * Write stringbuilder content to target file.
	 * @param stringBuilder
	 * @param feedInfo
	 */
	public static void writeFile(final StringBuilder stringBuilder, final FeedInfo feedInfo) {

		String targetLocation = feedInfo.getStrDestLocName();
		String targetName = feedInfo.getStrDestObjName();

		// If the target location isn't defined, use the source location instead
		if (targetLocation == null || targetLocation.equals("")) {
			System.out.println("Appears target location hasn't been set. Using source location instead.");
			targetLocation = feedInfo.getStrSrcLocName();
		}

		// If the target name isn't defined, use the source name with an appendage of '_output'
		if (targetName == null || targetName.equals("")) {
			System.out.println("Appears target name hasn't been provided. Using '" + feedInfo.getStrSrcObjName() + "_output' instead.");
			targetName = feedInfo.getStrSrcObjName() + "_output";
		}
		final String finalTargetFile = targetName;
		final File file = new File(finalTargetFile);

		BufferedWriter bufferedWriter = null;
		try {
			// If file doesn't exist, create it.
			if (!file.exists()) {
				file.createNewFile();
			}

			FileWriter fileWriter = new FileWriter(file.getAbsolutePath(), true);
			bufferedWriter = new BufferedWriter(fileWriter);
			bufferedWriter.write(stringBuilder.toString());
		}
		catch (IOException ioe) {
			System.out.println("Encountered exception writing to target file." + ioe.getMessage());
			System.exit(1);
		}
		finally {
			try {
				if (bufferedWriter != null) {
					bufferedWriter.flush();
					bufferedWriter.close();
				}
			}
			catch (IOException ex) {
				System.out.println("Encountered exception when closing buffered writer." + ex.getMessage());
			}
		}
	}

}
